<?php

namespace app\shop\events\wxMsgPush;

use app\shop\enums\order\OrderStatus;
use app\shop\enums\payment\OrderType;
use app\shop\exception\FailException;
use app\shop\logic\OrderLogic;
use app\shop\model\order\OrderModel;
use app\shop\model\PaymentTradeModel;
use app\shop\service\DeliveryService;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use think\helper\Arr;

/**
 * 小程序发货信息管理事件
 */
class MiniappOrderSettlement
{
    /**
     * 订单结算后处理事件
     * @param array $data
     * @return void
     * @throws FailException
     */
    public function handle(array $data): void
    {
        if (Arr::has($data, 'confirm_receive_time')) {
            $tradeNo         = $data['transaction_id'];
            $orderSettlement = (new DeliveryService())->checkOrderSettlement($tradeNo);
            if (!$orderSettlement) {
                return;
            }

            $trade = (new PaymentTradeModel())->where('trade_no', $tradeNo)->findOrEmpty();
            if ($trade->isEmpty()) {
                return;
            }

            if ($trade->order_type == OrderType::RECHARGE) {
                return;
            }

            $order = OrderModel::where('id', $trade->order_id)->field(['id', 'user_id', 'status'])->findOrEmpty();
            if ($order->isEmpty()) {
                return;
            }

            if ($order->status == OrderStatus::TO_RECEIVED) {
                (new OrderLogic())->receive([
                    'id'      => $order->id,
                    'user_id' => $order->user_id,
                ]);
            }
        }
    }
}